import React, { useState, useEffect } from 'react';
import { Card, Table, Button, InputNumber, message, Modal, Tag } from 'antd';
import { DeleteOutlined, ShoppingCartOutlined } from '@ant-design/icons';
import '../styles/Cart.css';

const Cart = () => {
  const [cartItems, setCartItems] = useState([]);
  const [selectedItems, setSelectedItems] = useState([]);
  const [totalPrice, setTotalPrice] = useState(0);

  useEffect(() => {
    // 模拟从本地存储获取购物车数据
    const mockCartItems = [
      {
        id: '1',
        movie: {
          title: '流浪地球2',
          poster: 'https://n.sinaimg.cn/sinakd20230123s/706/w1906h2800/20230123/9137-b383634783de89cde4d98c83c618be19.jpg',
          duration: '173分钟',
          type: '科幻/冒险'
        },
        cinema: {
          name: '万达影城（宁工店）',
          hall: '1号厅'
        },
        screening: {
          time: '2024-03-06 14:30',
          price: 45.00
        },
        seats: [
          { row: 5, col: 8 },
          { row: 5, col: 9 }
        ],
        quantity: 2
      },
      {
        id: '2',
        movie: {
          title: '满江红',
          poster: 'https://img2.jiemian.com/101/original/20230125/167457861579568000_a700xH.jpeg',
          duration: '159分钟',
          type: '悬疑/剧情'
        },
        cinema: {
          name: 'CGV影城（宁工店）',
          hall: '3号厅'
        },
        screening: {
          time: '2024-03-06 16:45',
          price: 38.00
        },
        seats: [
          { row: 7, col: 5 }
        ],
        quantity: 1
      }
    ];
    setCartItems(mockCartItems);
  }, []);

  // 更新总价的副作用
  useEffect(() => {
    if (!cartItems.length || !selectedItems.length) {
      setTotalPrice(0);
      return;
    }

    const total = selectedItems.reduce((sum, itemId) => {
      const item = cartItems.find(cartItem => cartItem.id === itemId);
      if (item) {
        return sum + (item.screening.price * item.quantity);
      }
      return sum;
    }, 0);

    setTotalPrice(total);
  }, [selectedItems, cartItems]);

  const handleQuantityChange = (id, value) => {
    const newCartItems = cartItems.map(item => {
      if (item.id === id) {
        return { ...item, quantity: value };
      }
      return item;
    });
    setCartItems(newCartItems);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要从购物车中删除该商品吗？',
      onOk: () => {
        const newCartItems = cartItems.filter(item => item.id !== id);
        setCartItems(newCartItems);
        setSelectedItems(selectedItems.filter(itemId => itemId !== id));
        message.success('删除成功');
      }
    });
  };

  const handleCheckout = () => {
    if (selectedItems.length === 0) {
      message.warning('请选择要结算的商品');
      return;
    }
    // 这里应该跳转到结算页面
    message.success('即将跳转到结算页面');
  };

  const columns = [
    {
      title: '电影信息',
      dataIndex: 'movie',
      key: 'movie',
      render: (movie, record) => (
        <div className="movie-info">
          <img src={movie.poster} alt={movie.title} className="movie-poster" />
          <div className="movie-details">
            <h4>{movie.title}</h4>
            <p>{movie.duration} | {movie.type}</p>
            <p>{record.cinema.name} - {record.cinema.hall}</p>
            <p>{record.screening.time}</p>
            <div className="seats-info">
              {record.seats.map((seat, index) => (
                <Tag key={index}>{seat.row}排{seat.col}座</Tag>
              ))}
            </div>
          </div>
        </div>
      )
    },
    {
      title: '单价',
      dataIndex: 'screening',
      key: 'price',
      render: (screening) => `¥${screening.price.toFixed(2)}`
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      render: (quantity, record) => (
        <InputNumber
          min={1}
          max={5}
          value={quantity}
          onChange={(value) => handleQuantityChange(record.id, value)}
        />
      )
    },
    {
      title: '小计',
      key: 'subtotal',
      render: (_, record) => `¥${(record.screening.price * record.quantity).toFixed(2)}`
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button
          type="text"
          danger
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      )
    }
  ];

  return (
    <div className="cart-container">
      <Card title="我的购物车" className="cart-card">
        <Table
          columns={columns}
          dataSource={cartItems}
          rowKey="id"
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys: selectedItems,
            getCheckboxProps: (record) => ({
              name: record.id,
            }),
            onChange: (selectedRowKeys) => {
              console.log('Selected:', selectedRowKeys);
              setSelectedItems(selectedRowKeys);
            }
          }}
          pagination={false}
        />
        <div className="cart-footer">
          <div className="total-price">
            总计：<span className="price">¥{totalPrice.toFixed(2)}</span>
            <span style={{ marginLeft: '8px', color: '#666' }}>
              (已选 {selectedItems.length} 件)
            </span>
          </div>
          <Button
            type="primary"
            size="large"
            icon={<ShoppingCartOutlined />}
            onClick={handleCheckout}
            disabled={selectedItems.length === 0}
            className="checkout-button"
          >
            去结算
          </Button>
        </div>
      </Card>
    </div>
  );
};

export default Cart; 